<?php
namespace app\admin\controller\store;
use app\admin\controller\Controller;
use think\Db;
use think\Session;
/**
 * 客户管理
 * Class Store
 * @package app\admin\controller
 */
class Store extends Controller{
    /**
     * 客户列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index(){
        //主管理员获取全部客户，城市管理员获取该城市所有销售在跟客户，区域管理员获取该区域所有销售客户
        $iszilu=input('get.iszilu');
        if($iszilu){
            $where['iszilu']=['=',$iszilu];
        }
        $datatype=input('get.datatype');
        if($datatype){
            $where['datatype']=['=',$datatype];
        }
        $search=input('get.search');
        if($search){
            $where['name|phone']=['like','%'.$search.'%'];
        }
        $userinfo=Db::name('love_admin_user')->where(['id'=>Session::get('yoshop_admin')['user']['id']])->find();
        if($userinfo['type']==1){
            //主管理员
            $where['floweuserid']=['<>',0];
        }elseif ($userinfo['type']==2){
            //城市管理员
            $user=Db::name('love_admin_user')->where(['cityid'=>$userinfo['cityid'],'type'=>['in','4,5']])->select()->toArray();
            $ids=[];
            if($user){
                foreach ($user as $k=>$v){
                    $ids[]=$v['id'];
                }
            }
            $ids[]=$userinfo['id'];
            $where['floweuserid']=['in',$ids];
        }else{
            //区域管理员
            $user=Db::name('love_admin_user')->where(['areaid'=>$userinfo['areaid'],'type'=>['in','4,5']])->select()->toArray();
            $ids=[];
            if($user){
                foreach ($user as $k=>$v){
                    $ids[]=$v['id'];
                }
            }
            $ids[]=$userinfo['id'];
            $where['floweuserid']=['in',$ids];
        }
        $list=Db::name('love_customer')->where($where)->order('create_time desc')->paginate(15, false, [
            'query' => \request()->request()
        ]);
        return $this->fetch('index', compact('list'));
    }
    /**
     * 审核
     */
    public function shenhe(){
        $id=input('post.id');
        $status=input('post.status');//1:审核通过 2：驳回 3：重新分配
        $customerInfo=Db::name('love_customer')->where(['id'=>$id])->field('id,floweuserid')->find();
        if($status==1){
            //审核通过
            //更新客户状态为已失效
            $update=Db::name('love_customer')->where(['id'=>$id])->update(['status'=>5,'update_time'=>time()]);
            if($update){
                //写入操作日志
                $data['userid']=Session::get('yoshop_admin')['user']['id'];
                $data['datatype']=5;//操作类型 1:录入(进入资源池)  2：付订 3：签约 4 预失效 5.确认失效 6.驳回 7.放回资源池重新分配 8.系统分配 9.转出 10. 区域管理员将过期客户手动分配给其他人员
                $data['fenpeiid']=$customerInfo['floweuserid'];
                $data['customerid']=$id;
                $data['fromType']=1;
                $data['remark']="预失效申请通过";
                $data['create_time']=time();
                Db::name('love_log')->insert($data);
                return json(['code'=>1,'msg'=>'审核通过成功']);
            }
            return json(['code'=>-1,'msg'=>'操作失败']);
        }elseif ($status==2){
            //驳回
            //更新客户状态为跟进中
            $update=Db::name('love_customer')->where(['id'=>$id])->update(['status'=>1,'update_time'=>time()]);
            if($update){
                //写入操作日志
                $data['userid']=Session::get('yoshop_admin')['user']['id'];
                $data['datatype']=6;//操作类型 1:录入(进入资源池)  2：付订 3：签约 4 预失效 5.确认失效 6.驳回 7.放回资源池重新分配 8.系统分配 9.转出 10. 区域管理员将过期客户手动分配给其他人员
                $data['fenpeiid']=$customerInfo['floweuserid'];
                $data['customerid']=$id;
                $data['fromType']=1;
                $data['remark']="预失效申请驳回";
                $data['create_time']=time();
                Db::name('love_log')->insert($data);
                return json(['code'=>1,'msg'=>'驳回成功']);
            }
            return json(['code'=>-1,'msg'=>'操作失败']);
        }else{
            //重新分配，客户重新放入资源池
            $update=Db::name('love_customer')->where(['id'=>$id])->update(['status'=>1,'update_time'=>time(),'floweuserid'=>0,'fenpei_time'=>0,'visit_time'=>0]);
            if($update){
                //写入操作日志
                $data['userid']=Session::get('yoshop_admin')['user']['id'];
                $data['datatype']=7;//操作类型 1:录入(进入资源池)  2：付订 3：签约 4 预失效 5.确认失效 6.驳回 7.放回资源池重新分配 8.系统分配 9.转出 10. 区域管理员将过期客户手动分配给其他人员
                $data['fenpeiid']=$customerInfo['floweuserid'];
                $data['customerid']=$id;
                $data['fromType']=1;
                $data['remark']="放回资源池重新分配";
                $data['create_time']=time();
                Db::name('love_log')->insert($data);
                return json(['code'=>1,'msg'=>'重新分配成功']);
            }
            return json(['code'=>-1,'msg'=>'操作失败']);
        }
    }
    /**
     * 获取区域管理员下级所有人员
     */
    public function getuser(){
        $userinfo=Db::name('love_admin_user')->where(['id'=>Session::get('yoshop_admin')['user']['id']])->find();
        $users=Db::name('love_admin_user')->where(['type'=>['in','4,5'],'cityid'=>$userinfo['cityid']])->select()->toArray();
        foreach ($users as $k=>$v){
            $cityname=Db::name('love_area')->where(['id'=>$v['areaid']])->value('name');
            $users[$k]['name']=$cityname.'----'.$users[$k]['name'];
        }
        return json(['code'=>1,'msg'=>'获取成功','data'=>$users]);
    }
    /**
     * 转出
     */
    public function change(){
        $userid=input('post.userid');
        $customerid=input('post.cusid');
        //判断要转的销售是否当前正在跟进的销售
        $customerInfo=Db::name('love_customer')->where(['id'=>$customerid])->find();
        if($userid==$customerInfo['floweuserid']){
            return json(['code'=>-1,'msg'=>'当前销售正在跟进中，重新选择','data'=>[]]);
        }
        //更新客户表
        Db::name('love_customer')->where(['id'=>$customerid])->update(['status'=>1,'floweuserid'=>$userid,'visit_time'=>0,'fenpei_time'=>0]);
        //写入日志记录
        $data['userid']=Session::get('yoshop_admin')['user']['id'];
        $data['datatype']=9;//操作类型 1:录入(进入资源池)  2：付订 3：签约 4 预失效 5.确认失效 6.驳回 7.放回资源池重新分配 8.系统分配 9.转出 10. 区域管理员将过期客户手动分配给其他人员
        $data['fenpeiid']=$userid;
        $data['customerid']=$customerid;
        $data['fromType']=1;
        $data['remark']="后台转出";
        $data['create_time']=time();
        Db::name('love_log')->insert($data);
        return json(['code'=>1,'msg'=>'转出成功']);
    }
    /**
     * 客户详情信息
     */
    public function getinfo($id){
        if(empty($id)){
            return $this->renderError('客户id不能为空');
        }
        //查看，获取客户当前基本信息 ,凭证信息，跟进信息
        $customerInfo=Db::name('love_customer')->where(['id'=>$id])->find();
        if(empty($customerInfo)){
            return $this->renderError('未获取到客户信息');
        }
        //获取凭证信息，只获取当前跟进人填写的凭证信息，跟进信息
        //意向楼盘
        $build=Db::name('love_building')->where(['id'=>$customerInfo['loupanid']])->field('id,name')->find();
        if($build){
            $customerInfo['buildName']=$build['name'];
        }else{
            $customerInfo['buildName']='暂无';
        }
        //城市，区域
        $areaInfo=Db::name('love_area')->where(['id'=>$customerInfo['cityid']])->field('id,name')->find();
        if($areaInfo){
            $customerInfo['cityname']=$areaInfo['name'];
        }else{
            $customerInfo['cityname']='暂无';
        }
        $cityInfo=Db::name('love_area')->where(['id'=>$customerInfo['areaid']])->field('id,name')->find();
        if($cityInfo){
            $customerInfo['areaname']=$cityInfo['name'];
        }else{
            $customerInfo['areaname']='暂无';
        }
        //录入人信息
        $userInfo=Db::name('love_admin_user')->where(['id'=>$customerInfo['inputuserid']])->field('id,name')->find();
        $customerInfo['inputName']=$userInfo['name'];
        
        
        //跟进人信息
        $userInfos=Db::name('love_admin_user')->where(['id'=>$customerInfo['floweuserid']])->field('id,user_name,name')->find();
        $customerInfo['genjinrenName']=$userInfos['name'];
        $customerInfo['genjinrenphone']=$userInfos['user_name'];
        //获取到访凭证，签约备注，已买备注信息
        $folowInfo=Db::name('love_follow')->where(['customerId'=>$id,'userId'=>$customerInfo['floweuserid'],'type'=>['in','2,3,4']])->order('type')->select()->toArray();
        $customerInfo['daofanginfo']=[];
        $customerInfo['qianyueinfo']=[];
        $customerInfo['yimaiinfo']=[];
        if($folowInfo){
            foreach($folowInfo as $k=>$v){
                $folowInfo[$k]['imageInfo']=$this->getImageUrl(json_decode($v['imageIds'],'true'));
                $folowInfo[$k]['createTime']=date('Y-m-d H:i:s',$v['createTime']);
                if($v['type']==2){
                    $customerInfo['daofanginfo']=$folowInfo[$k];
                }elseif ($v['type']==3){
                    $customerInfo['qianyueinfo']=$folowInfo[$k];
                }else{
                    $customerInfo['yimaiinfo']=$folowInfo[$k];
                }
            }
        }
        //获取跟进信息
        $fol=Db::name('love_follow')->where(['customerId'=>$id,'userId'=>$customerInfo['floweuserid'],'type'=>1])->order('createTime desc')->select()->toArray();
        //跟进人名称
        if($fol){
            foreach($fol as $k=>$v){
                $fol[$k]['genjinrenname']=Db::name('love_admin_user')->where(['id'=>$v['userid']])->field('id,name')->find()['name'];
                $fol[$k]['createTime']=date('Y-m-d H:i:s',$v['createTime']);
            }
        }
        $customerInfo['fol']=$fol;
        $customerInfo['createTime']=date('Y-m-d H:i:s',$customerInfo['create_time']);
        if($customerInfo['visit_time']){
            $customerInfo['visitTime']=date('Y-m-d H:i:s',$customerInfo['visit_time']);
        }
        return $this->fetch('getinfo', compact('customerInfo'));
    }
    /**
     * 获取图片链接
     */
    private function getImageUrl($ids){
        $imageInfos=Db::name('upload_file')->where('file_id','in',$ids)->select();
        $arr=[];
        if($imageInfos){
            foreach($imageInfos as $k=>$v){
                $arr[]=$v['file_url'].'/'.$v['file_name'];
            }
        }
        return $arr;
    }
    /**
     * 重置客户
     */
    public function recovery(){
        $id=input('post.id');
        $res=Db::name('love_customer')->where(['id'=>$id])->find();
        $a=Db::name('love_customer')->where(['id'=>$id])->update(['status'=>1,'fenpei_time'=>0,'floweuserid'=>0,'update_time'=>time(),'dingjin'=>0,'qianyue'=>0]);
        $logdata['userid']=0;
        $logdata['datatype']=12;
        $logdata['fenpeiid']=$res['floweuserid'];
        $logdata['customerid']=$id;
        $logdata['fromType']=1;
        $logdata['remark']='卖/出租客户后台重置';
        $logdata['create_time']=time();
        $b=Db::name('love_log')->insert($logdata);
        if($a&&$b){
            return json(['code'=>1,'msg'=>'重置成功']);
        }
        return json(['code'=>-1,'msg'=>'重置失败']);
    }


    /**
     * 客户列表数据导出
     */
    public function goodsExport(){
        if (!$this->goodsFinanceExport($order_source = 10,$this->request->param())) {
            return $this->renderError('操作失败');
        }
        return $this->goodsFinanceExport($order_source = 10,$this->request->param());
    }
    public function goodsFinanceExport($order_source,$query = []){
        header("Content-type:text/html;charset=utf-8");
        $mpName = '客户列表';
        $limit = 500;//每次只从数据库取50000条以防变量缓存太大
        // buffer计数器
        $cnt = 0;
        set_time_limit(0);
        //计算总的数据
        $sqlCount = $this->getGoodsFinanceExport($order_source,$query,0, $limit,true);
$ccount=count($sqlCount);
        if($ccount<1){
            $this->error = '无数据导出';
            return false;
        }
        $xlsTitle = [
            '客户id', '录入人', '录入人电话', '客户名称', '客户电话', '跟进人', '跟进人电话', '意向楼盘名称', '状态',
            '添加时间',
        ];

        $userinfos=Db::name('love_admin_user')->where(['id'=>Session::get('yoshop_admin')['user']['id']])->find();
        $fileName = $userinfos['name'];// 文件名称可根据自己情况设定
        // 输出Excel文件头，可把user.csv换成你要的文件名
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');

        $fileNameArr = array();
        // 逐行取出数据，不浪费内存
        for ($i = 0; $i < ceil($ccount / $limit); $i++) {

            $fp = fopen($fileName . '_' . $i . '.csv', 'w'); //生成临时文件
            fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));// 转码 防止乱码(比如微信昵称)
            // chmod('attack_ip_info_' . $i . '.csv',777);//修改可执行权限
            $fileNameArr[] = $fileName . '_' . $i . '.csv'; // 将数据通过fputcsv写到文件句柄
            fputcsv($fp, $xlsTitle);
            $start = $i * $limit;
            $dataArr = $this->getGoodsFinanceExport($order_source,$query, $start, $limit,false);

            foreach ($dataArr as $a) {
                $cnt++;
                if ($limit == $cnt) {
                    //刷新一下输出buffer，防止由于数据过多造成问题
                    ob_flush();
                    flush();
                    $cnt = 0;
                }
                fputcsv($fp, $a);
            }
            fclose($fp);  //每生成一个文件关闭
        }

        //进行多个文件压缩
        $zip = new \ZipArchive();
        $filename = $fileName . ".zip";
        $zip->open($filename, $zip::CREATE);   //打开压缩包
        foreach ($fileNameArr as $file) {
            $zip->addFile($file, basename($file));   //向压缩包中添加文件
        }
        $zip->close();  //关闭压缩包
        foreach ($fileNameArr as $file) {
            unlink($file); //删除csv临时文件
        }

        //输出压缩文件提供下载
        header("Cache-Control: max-age=0");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . basename($filename)); // 文件名
        header("Content-Type: application/zip"); // zip格式的
        header("Content-Transfer-Encoding: binary"); //
        header('Content-Length: ' . filesize($filename)); //
        @readfile($filename);//输出文件;
        unlink($filename); //删除压缩包临时文件

    }
    public function getGoodsFinanceExport($order_source,$query = [],$start, $limit,$count = false){

        // 获取数据列表
        $userinfo=Db::name('love_admin_user')->where(['id'=>Session::get('yoshop_admin')['user']['id']])->find();
        if($userinfo['type']==1){
            //主管理员
            $where['floweuserid']=['<>',0];
        }elseif ($userinfo['type']==2){
            //城市管理员
            $user=Db::name('love_admin_user')->where(['cityid'=>$userinfo['cityid'],'type'=>['in','4,5']])->select()->toArray();
            $ids=[];
            if($user){
                foreach ($user as $k=>$v){
                    $ids[]=$v['id'];
                }
            }
            $ids[]=$userinfo['id'];
            $where['floweuserid']=['in',$ids];
        }else{
            //区域管理员
            $user=Db::name('love_admin_user')->where(['areaid'=>$userinfo['areaid'],'type'=>['in','4,5']])->select()->toArray();
            $ids=[];
            if($user){
                foreach ($user as $k=>$v){
                    $ids[]=$v['id'];
                }
            }
            $ids[]=$userinfo['id'];
            $where['floweuserid']=['in',$ids];
        }
        $list=Db::name('love_customer')->where($where)->order('create_time desc')->select();
        // 表格内容
        $dataArray = [];
        foreach ($list as $order) {
            //1:跟进中 2：已付订 3.已签约 4.预失效 5.失效
            if($order['status']==1){
                $str='跟进中';
            }
            if($order['status']==2){
                $str='已付订';
            }
            if($order['status']==3){
                $str='已签约';
            }
            if($order['status']==4){
                $str='预失效';
            }
            if($order['status']==5){
                $str='失效';
            }
            $dataArray[] = [
                '客户id' => $order['id'],
                '录入人' => upname($order['inputuserid']),
                '录入人电话' =>upphone($order['inputuserid']),
                '客户名称' => $order['name'],
                '客户电话' =>$order['phone'],
                '跟进人' => upname($order['floweuserid']),
                '跟进人电话' => upphone($order['floweuserid']),
                '意向楼盘名称' => getgenjloupanname($order['loupanid']),
                '客户状态' => $str,
                '添加时间' =>date('Y-m-d H:i:s',$order['create_time']),
            ];
        }
        return  $dataArray;
    }

}